/*Copyright ©2015 TommyLemon(https://github.com/TommyLemon)

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.*/

package zuo.biao.library.ui;

import ohos.aafwk.ability.Ability;
import ohos.agp.components.Component;
import ohos.agp.components.ComponentContainer;
import ohos.agp.components.DirectionalLayout;
import ohos.agp.components.ListContainer;
import ohos.agp.components.Text;
import zuo.biao.library.ResourceTable;
import zuo.biao.library.base.BaseView;
import zuo.biao.library.model.Entry;
import zuo.biao.library.model.GridPickerConfig;
import zuo.biao.library.util.ResTUtil;
import zuo.biao.library.util.ScreenUtil;
import zuo.biao.library.util.StringUtil;

import java.util.ArrayList;
import java.util.List;

import static ohos.agp.components.ComponentContainer.LayoutConfig.MATCH_PARENT;

/**网格选择器View
 * @author Lemon
 * @must 调用init方法
 * @use 参考 .DemoView
 */
public class GridPickerView extends BaseView<List<Entry<Integer, String>>> {
	private static final String TAG = "GridPickerView";

	/**tabs切换和gridView的内容切换
	 */
	public interface OnTabClickListener {

		void onTabClick(int tabPosition, Text tvTab);
	}

	private OnTabClickListener onTabClickListener;
	public void setOnTabClickListener(OnTabClickListener onTabClickListener) {
		this.onTabClickListener = onTabClickListener;
	}


	private ListContainer.ItemSelectedListener onItemSelectedListener;
	public void setOnItemSelectedListener(ListContainer.ItemSelectedListener onItemSelectedListener) {
		this.onItemSelectedListener = onItemSelectedListener;
	}

	private int contentHeight;
	public GridPickerView(Ability context) {
		super(context, ResourceTable.Layout_grid_picker_view);
		contentHeight = 300;
	}

	public DirectionalLayout llGridPickerViewTabContainer;
	public ListContainer gvGridPickerView;
	/**获取View
	 * @return Component
	 */
	@Override
	public Component createView() {
		llGridPickerViewTabContainer = findView(ResourceTable.Id_llGridPickerViewTabContainer);
		gvGridPickerView = findView(ResourceTable.Id_gvGridPickerView);

		return super.createView();
	}


	/**
	 * 获取配置列表
	 * @return getConfigList
	 */
	public ArrayList<GridPickerConfig> getConfigList() {
		return configList;
	}

	/**
	 * 获取已选择列表
	 * @return getSelectedItemList
	 */
	public ArrayList<String> getSelectedItemList() {
		ArrayList<String> list = new ArrayList<String>();
		for (GridPickerConfig gpcb : configList) {
			list.add(gpcb.getSelectedItemName());
		}
		return list;
	}

	/**
	 * 获取tab
	 * @return getTabCount
	 */
	public int getTabCount() {
		return configList == null ? 0 : configList.size();
	}

	/**
	 * isOnFirstTab
	 * @return isOnFirstTab
	 */
	public boolean isOnFirstTab() {
		return getTabCount() <= 0 ? false : getCurrentTabPosition() <= 0;
	}

	/**
	 * isOnLastTab
	 * @return boolean
	 */
	public boolean isOnLastTab() {
		return getTabCount() <= 0 ? false : getCurrentTabPosition() >= getTabCount() - 1;
	}

	private int currentTabPosition;

	/**
	 * 获取当前tab位置
	 * @return getCurrentTabPosition
	 */
	public int getCurrentTabPosition() {
		return currentTabPosition;
	}

	private String currentTabName;

	/**
	 * 获取当前tabname
	 * @return
	 */
	public String getCurrentTabName() {
		return currentTabName;
	}
	private String currentTabSuffix;

	/**
	 * getCurrentTabSuffix
	 * @return getCurrentTabSuffix
	 */
	public String getCurrentTabSuffix() {
		return currentTabSuffix;
	}


	protected String currentSelectedItemName;

	/**
	 * 获取当前已选名字
	 * @return getCurrentSelectedItemName
	 */
	public String getCurrentSelectedItemName() {
		return currentSelectedItemName;
	}
	protected int currentSelectedItemPosition;

	/**
	 * 获取当前选择item
	 * @return getCurrentSelectedItemPosition
	 */
	public int getCurrentSelectedItemPosition() {
		return currentSelectedItemPosition;
	}

	/**
	 * 获取选择itemname
	 * @param tabPosition tab位置
	 * @return getSelectedItemName
	 */
	public String getSelectedItemName(int tabPosition) {
		return configList.get(tabPosition).getSelectedItemName();
	}

	/**
	 * 获取选择item pos
	 * @param tabPosition tabpos
	 * @return getSelectedItemPosition
	 */
	public int getSelectedItemPosition(int tabPosition) {
		return configList.get(tabPosition).getSelectedItemPostion();
	}

	/**
	 *  获取数据
	 * @return getList
	 */
	public List<Entry<Integer, String>> getList() {
		return adapter == null ? null : adapter.data;
	}


	@Override
	public void bindView(List<Entry<Integer, String>> l){/*do nothing,必须init**/}


	/**初始化，必须使用且只能使用一次
	 * @param configList 配置列表
	 * @param lastList lastList
	 */
	public final void init(ArrayList<GridPickerConfig> configList, List<Entry<Integer, String>> lastList) {
		if (configList == null || configList.size() <= 0) {
			return;
		}

		currentTabPosition = configList.size() - 1;
		currentTabName = configList.get(currentTabPosition).getTabName();

		int tabWidth = configList.size() < 4 ? ScreenUtil.getScreenWidth(context) / configList.size() : 3;
		llGridPickerViewTabContainer.removeAllComponents();
		for (int i = 0; i < configList.size(); i++) {//需要重新设置来保持每个tvTab宽度一致

			addTab(i, tabWidth, StringUtil.getTrimedString(configList.get(i)));
		}
		llGridPickerViewTabContainer.getComponentAt(currentTabPosition)
		.setBackground(ResTUtil.getElement(context,ResourceTable.Color_material_lighter_gray));

		this.configList = configList;

		bindView(currentTabPosition, lastList, configList.get(currentTabPosition).getSelectedItemPostion());
	}



	/**添加tab
	 * @param tabPosition tabpos
	 * @param tabWidth width
	 * @param name name
	 */
	private void addTab(final int tabPosition, int tabWidth, String name) {
		if (StringUtil.isNotEmpty(name, true) == false) {
			return;
		}
		name = StringUtil.getTrimedString(name);

		final Text tvTab = new Text(context);
		tvTab.setLayoutConfig(new ComponentContainer.LayoutConfig(tabWidth,MATCH_PARENT));
		//		tvTab.setPaddingRelative(4, 12, 4, 12);
		tvTab.setTextColor(ResTUtil.getNewColor(context,ResourceTable.Color_black));
		tvTab.setTextSize(18);
		tvTab.setText(name);
		tvTab.setClickedListener(new Component.ClickedListener() {
			@Override
			public void onClick(Component component) {
				if (tabPosition == getCurrentTabPosition()) {
					return;
				}

				if (onTabClickListener != null) {
					onTabClickListener.onTabClick(tabPosition, tvTab);
					return;
				}
				//点击就是要切换list，这些配置都要改bindView(tabSuffix, tabPosition, tabName, list, numColumns, maxShowRows, itemPosition)
			}
		});
		llGridPickerViewTabContainer.addComponent(tvTab);
	}



	private static final int MAX_NUM_TABS = 12;//最大标签数量

	private ArrayList<GridPickerConfig> configList;
	private GridPickerAdapter adapter;
	/**设置并显示内容//可能导致每次都不变
	 * @param tabPosition tabPosition
	 * @param list data
	 */
	public void bindView(final int tabPosition, List<Entry<Integer, String>> list) {
		bindView(tabPosition, list, getSelectedItemPosition(tabPosition));
	}
	/**
	 * @param tabPosition tabPosition
	 * @param list data
	 * @param itemPosition itemPosition
	 */
	public void bindView(final int tabPosition, List<Entry<Integer, String>> list, int itemPosition) {//GridView
		if (configList == null || configList.size() <= 0) {
			return;
		}
		GridPickerConfig gpcb = configList.get(tabPosition);
		if (gpcb == null) {
			return;
		}

		if (list == null || list.size() <= 0) {
			return;
		}
		if (tabPosition >= MAX_NUM_TABS) {
			return;
		}

		itemPosition = getItemPosition(itemPosition, list);

		int numColumns = gpcb.getNumColumns();
		if (numColumns <= 0) {
			numColumns = 3;
		}

		int maxShowRows = gpcb.getMaxShowRows();
		if (maxShowRows <= 0) {
			maxShowRows = 5;
		}

		//Tabs<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

		doOnItemSelected(tabPosition, itemPosition, list.get(itemPosition).getValue());

		//Tabs>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>


		//gridView<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

		adapter = new GridPickerAdapter(context,ResourceTable.Layout_list_item,list == null ? null : new ArrayList<Entry<Integer, String>>(list)){

			@Override
			protected void bind(ViewHolder holder, Object s, int position) {
				holder.setText(ResourceTable.Id_txt_name, (String) s);
			}
		};
		adapter.setNumColumns(contentHeight/maxShowRows);
		adapter.setOnItemClickListener(new GridPickerAdapter.OnItemClickListener() {
			@Override
			public void onItemClick(Component component, int position) {
				currentSelectedItemName = adapter.getItem(position).toString();
				if (isOnLastTab() == false && onItemSelectedListener != null) {
					onItemSelectedListener.onItemSelected(gvGridPickerView, component, position, 0);
					return;
				}
				doOnItemSelected(tabPosition, position, adapter.getItem(position).toString());
			}
		});

		gvGridPickerView.setItemProvider(adapter);
		gvGridPickerView.scrollTo(itemPosition);

		//gridView>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

	}

	private int length;
	/**获取itemPosition，解决部分不可点击的item被选中的问题
	 * @param itemPosition itemPosition
	 * @param list data
	 * @return getItemPosition
	 */
	private int getItemPosition(int itemPosition, List<Entry<Integer, String>> list) {
		if (itemPosition < 0) {
			itemPosition = 0;
		} else if (itemPosition >= list.size()) {
			itemPosition = list.size() - 1;
		}

		if (isItemEnabled(list, itemPosition) == false) {
			length = Math.max(itemPosition, list.size() - itemPosition);
			for (int i = 1; i <= length; i++) {
				if (isItemEnabled(list, itemPosition - i)) {
					return itemPosition - i;
				}
				if (isItemEnabled(list, itemPosition + i)) {
					return itemPosition + i;
				}
			}
		}

		return itemPosition;
	}

	private boolean isItemEnabled(List<Entry<Integer, String>> list, int itemPosition) {
		return list != null && itemPosition >= 0 && itemPosition < list.size()
				&& list.get(itemPosition).getKey() == GridPickerAdapter.TYPE_CONTNET_ENABLE;
	}


	/**在onItemSelected时响应,
	 * 之后可能会跳转到下一个tab，导致 tabPositionWhenItemSelect+=1; selectedItemPosition = 0;
	 * @param tabPosition tabPosition
	 * @param itemPosition itemPosition
	 * @param itemName itemName
	 */
	public void doOnItemSelected(int tabPosition, int itemPosition, String itemName) {
		currentTabPosition = tabPosition < getTabCount() ? tabPosition : getTabCount() - 1;
		currentSelectedItemPosition = itemPosition;
		currentSelectedItemName = StringUtil.getTrimedString(itemName);

		configList.set(currentTabPosition, configList.get(currentTabPosition).set(currentSelectedItemName, itemPosition));

		for (int i = 0; i < llGridPickerViewTabContainer.getChildCount(); i++) {
			((Text) llGridPickerViewTabContainer.getComponentAt(i)).setText("" + configList.get(i).getTabName());
			llGridPickerViewTabContainer.getComponentAt(i).setBackground(
					i == tabPosition ? ResTUtil.getElement(context,ResourceTable.Color_alpha_1) : ResTUtil.getElement(context,ResourceTable.Color_t_lighter_gray));
		}
	}


}
